package gov.pbc.nn.kjgl.tech.dao;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.dao.CommonJdbcDao;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.entity.Technician;
import gov.pbc.nn.kjgl.entity.TechnicianHistory;

@Repository
public class TechnicianDao extends AbstractHibernateDao {

	@Resource(name = PbcnnCoreJdbcDao.BEAN_ID)
	private PbcnnCoreJdbcDao coreJdbcDao;
	@Resource(name = CommonJdbcDao.BEAN_ID)
	private CommonJdbcDao jdbcDao;

	public void getAll(Page<Technician> page, Criteria criteria) {
		Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		Dept zzDept = (Dept) SecurityUtils.getZZByDept(dept);
		DetachedCriteria dc = this.buildDetachedCriteria(criteria, Technician.class);
		dc.add(Restrictions.eq("invalid", false));
		if (!Dept.NANNING.equals(zzDept.getId())) {
			dc.add(Restrictions.eq("deptId", dept.getId()));
		}
		this.pagingQuery(page, dc);
	}

	public Technician getMyTechnician() {
		DetachedCriteria dc = DetachedCriteria.forClass(Technician.class);
		dc.add(Restrictions.eq("invalid", false));
		dc.add(Restrictions.eq("username", ContextHolder.getLoginUserName()));
		Collection<Technician> col = (Collection<Technician>) this.query(dc);
		if (col.isEmpty()) {
			return null;
		}
		return col.iterator().next();
	}

	public void getTechnicianHistory(Page<TechnicianHistory> page, String originalId) throws Exception {
		DetachedCriteria dc = DetachedCriteria.forClass(TechnicianHistory.class);
		dc.add(Restrictions.eq("originalId", originalId));
		dc.addOrder(Order.desc("updateDate"));
		this.pagingQuery(page, dc);
		;
	}

	public void save(List<Technician> list) {
		for (Technician technician : list) {
			EntityState s = EntityUtils.getState(technician);
			if (s == EntityState.NEW) {
				this.save(technician);
			} else if (s == EntityState.MODIFIED) {
				saveHistory(technician.getId());
				this.update(technician);
			}
		}
	}

	public void delete(String id) {
		this.delete(id, Technician.class);
	}

	private void saveHistory(final String id) {
		Technician t = (Technician) this.get(id, Technician.class);
		String str = JSON.toJSONString(t, SerializerFeature.WriteDateUseDateFormat);
		TechnicianHistory th = JSON.parseObject(str, TechnicianHistory.class);
		System.out.println(th.getDeptId());
		this.save(th);
	}

	public List<Map<String, Object>> getUsers(String username) {
		List<Map<String, Object>> lists = null;
		if (username != null) {
			String sql = "select u.USERNAME_,u.CNAME_ ,d.ID_ as DEPT_ID_,d.NAME_ AS DEPT_NAME_  from t_user u  INNER JOIN bdf2_user_dept ud on ud.USERNAME_=u.USERNAME_ INNER JOIN  t_dept d ON ud.DEPT_ID_=d.ID_  where d.id_=? and u.CNAME_ like concat(?,'%') or d.NAME_ like concat('%',?,'%') ";
			lists = this.coreJdbcDao.getJdbcTemplate().queryForList(sql,
					new String[] { ContextHolder.getLoginUser().getDepts().get(0).getId(), username, username });

		} else {
			String sql1 = "select u.USERNAME_,u.CNAME_ ,d.ID_ as DEPT_ID_,d.NAME_ AS DEPT_NAME_  from t_user u  INNER JOIN bdf2_user_dept ud on ud.USERNAME_=u.USERNAME_ INNER JOIN  t_dept d ON ud.DEPT_ID_=d.ID_  where  d.id_=?";
			lists = this.coreJdbcDao.getJdbcTemplate().queryForList(sql1,
					new String[] { ContextHolder.getLoginUser().getDepts().get(0).getId() });
		}
		return lists;
	}
}
